<template>
  <div class="message-export">
    <el-card class="export-card">
      <template #header>
        <div class="card-header">
          <div class="header-left">
            <el-input
              v-model="searchQuery"
              placeholder="搜索导出任务名称"
              class="search-input"
              clearable
              @clear="handleSearch"
              @keyup.enter="handleSearch"
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
            <el-button type="primary" @click="handleCreateExport">
              <el-icon><Plus /></el-icon>新建导出
            </el-button>
          </div>
          <div class="header-right">
            <el-button-group>
              <el-button @click="activeTab = 'tasks'">导出任务</el-button>
              <el-button @click="activeTab = 'templates'">导出模板</el-button>
            </el-button-group>
          </div>
        </div>
      </template>

      <!-- 导出任务列表 -->
      <div v-show="activeTab === 'tasks'">
        <el-table
          :data="exportTasks"
          border
          v-loading="loading"
          style="width: 100%"
        >
          <el-table-column prop="name" label="任务名称" min-width="150" />
          <el-table-column prop="templateName" label="导出模板" width="150" />
          <el-table-column prop="format" label="导出格式" width="100">
            <template #default="scope">
              <el-tag>{{ scope.row.format.toUpperCase() }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="status" label="状态" width="100">
            <template #default="scope">
              <el-tag :type="getStatusType(scope.row.status)">
                {{ getStatusLabel(scope.row.status) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="progress" label="进度" width="200">
            <template #default="scope">
              <el-progress
                :percentage="scope.row.progress"
                :status="getProgressStatus(scope.row.status)"
              />
            </template>
          </el-table-column>
          <el-table-column prop="createTime" label="创建时间" width="180" />
          <el-table-column prop="completeTime" label="完成时间" width="180" />
          <el-table-column label="操作" width="200" fixed="right">
            <template #default="scope">
              <el-button
                type="primary"
                link
                @click="handleDownload(scope.row)"
                v-if="scope.row.status === 'completed'"
              >下载</el-button>
              <el-button
                type="primary"
                link
                @click="handleRetry(scope.row)"
                v-if="scope.row.status === 'failed'"
              >重试</el-button>
              <el-button
                type="danger"
                link
                @click="handleDelete(scope.row)"
                v-if="['completed', 'failed'].includes(scope.row.status)"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination-container">
          <el-pagination
            v-model:current-page="pageNum"
            v-model:page-size="pageSize"
            :total="total"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>

      <!-- 导出模板列表 -->
      <div v-show="activeTab === 'templates'">
        <div class="template-header">
          <el-button type="primary" @click="handleCreateTemplate">
            <el-icon><Plus /></el-icon>新建模板
          </el-button>
        </div>
        <el-table
          :data="exportTemplates"
          border
          style="width: 100%"
        >
          <el-table-column prop="name" label="模板名称" min-width="150" />
          <el-table-column prop="description" label="描述" min-width="200" show-overflow-tooltip />
          <el-table-column prop="format" label="导出格式" width="100">
            <template #default="scope">
              <el-tag>{{ scope.row.format.toUpperCase() }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="fields" label="导出字段" min-width="200" show-overflow-tooltip>
            <template #default="scope">
              {{ scope.row.fields.map(f => f.label).join(', ') }}
            </template>
          </el-table-column>
          <el-table-column prop="createTime" label="创建时间" width="180" />
          <el-table-column label="操作" width="200" fixed="right">
            <template #default="scope">
              <el-button
                type="primary"
                link
                @click="handleEditTemplate(scope.row)"
              >编辑</el-button>
              <el-button
                type="primary"
                link
                @click="handleCopyTemplate(scope.row)"
              >复制</el-button>
              <el-button
                type="danger"
                link
                @click="handleDeleteTemplate(scope.row)"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-card>

    <!-- 新建导出对话框 -->
    <el-dialog
      v-model="exportDialogVisible"
      :title="exportForm.id ? '编辑导出任务' : '新建导出任务'"
      width="600px"
    >
      <el-form
        ref="exportFormRef"
        :model="exportForm"
        :rules="exportRules"
        label-width="100px"
      >
        <el-form-item label="任务名称" prop="name">
          <el-input v-model="exportForm.name" placeholder="请输入任务名称" />
        </el-form-item>
        <el-form-item label="导出模板" prop="templateId">
          <el-select
            v-model="exportForm.templateId"
            placeholder="请选择导出模板"
            @change="handleTemplateChange"
          >
            <el-option
              v-for="template in exportTemplates"
              :key="template.id"
              :label="template.name"
              :value="template.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="导出格式" prop="format">
          <el-radio-group v-model="exportForm.format">
            <el-radio label="excel">Excel</el-radio>
            <el-radio label="pdf">PDF</el-radio>
            <el-radio label="word">Word</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="导出条件">
          <el-form-item label="时间范围" prop="timeRange">
            <el-date-picker
              v-model="exportForm.timeRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="YYYY-MM-DD"
            />
          </el-form-item>
          <el-form-item label="消息类型" prop="types">
            <el-select
              v-model="exportForm.types"
              multiple
              placeholder="请选择消息类型"
            >
              <el-option
                v-for="type in messageTypes"
                :key="type.value"
                :label="type.label"
                :value="type.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="处理状态" prop="status">
            <el-select
              v-model="exportForm.status"
              multiple
              placeholder="请选择处理状态"
            >
              <el-option
                v-for="status in processStatus"
                :key="status.value"
                :label="status.label"
                :value="status.value"
              />
            </el-select>
          </el-form-item>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="exportDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitExport" :loading="submitting">
          确定
        </el-button>
      </template>
    </el-dialog>

    <!-- 模板编辑对话框 -->
    <el-dialog
      v-model="templateDialogVisible"
      :title="templateForm.id ? '编辑模板' : '新建模板'"
      width="800px"
    >
      <el-form
        ref="templateFormRef"
        :model="templateForm"
        :rules="templateRules"
        label-width="100px"
      >
        <el-form-item label="模板名称" prop="name">
          <el-input v-model="templateForm.name" placeholder="请输入模板名称" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input
            v-model="templateForm.description"
            type="textarea"
            :rows="2"
            placeholder="请输入模板描述"
          />
        </el-form-item>
        <el-form-item label="导出格式" prop="format">
          <el-radio-group v-model="templateForm.format">
            <el-radio label="excel">Excel</el-radio>
            <el-radio label="pdf">PDF</el-radio>
            <el-radio label="word">Word</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="导出字段" prop="fields">
          <div class="fields-container">
            <div class="fields-list">
              <el-checkbox-group v-model="templateForm.selectedFields">
                <el-checkbox
                  v-for="field in availableFields"
                  :key="field.value"
                  :label="field.value"
                >
                  {{ field.label }}
                </el-checkbox>
              </el-checkbox-group>
            </div>
            <div class="fields-actions">
              <el-button-group>
                <el-button @click="moveField('up')">
                  <el-icon><ArrowUp /></el-icon>
                </el-button>
                <el-button @click="moveField('down')">
                  <el-icon><ArrowDown /></el-icon>
                </el-button>
              </el-button-group>
            </div>
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="templateDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitTemplate" :loading="submitting">
          确定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Plus, ArrowUp, ArrowDown } from '@element-plus/icons-vue'
import {
  getExportTaskList,
  createExportTask,
  deleteExportTask,
  retryExportTask,
  downloadExportFile,
  getExportTemplateList,
  createExportTemplate,
  updateExportTemplate,
  deleteExportTemplate,
  copyExportTemplate
} from '@/api/message'

// 数据加载状态
const loading = ref(false)
const submitting = ref(false)

// 分页数据
const pageNum = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 搜索相关
const searchQuery = ref('')
const activeTab = ref('tasks')

// 对话框显示状态
const exportDialogVisible = ref(false)
const templateDialogVisible = ref(false)

// 列表数据
const exportTasks = ref([])
const exportTemplates = ref([])

// 表单引用
const exportFormRef = ref(null)
const templateFormRef = ref(null)

// 导出任务表单
const exportForm = reactive({
  id: '',
  name: '',
  templateId: '',
  format: 'excel',
  timeRange: [],
  types: [],
  status: []
})

// 导出模板表单
const templateForm = reactive({
  id: '',
  name: '',
  description: '',
  format: 'excel',
  selectedFields: []
})

// 表单验证规则
const exportRules = {
  name: [{ required: true, message: '请输入任务名称', trigger: 'blur' }],
  templateId: [{ required: true, message: '请选择导出模板', trigger: 'change' }],
  format: [{ required: true, message: '请选择导出格式', trigger: 'change' }]
}

const templateRules = {
  name: [{ required: true, message: '请输入模板名称', trigger: 'blur' }],
  format: [{ required: true, message: '请选择导出格式', trigger: 'change' }],
  selectedFields: [{ required: true, message: '请选择导出字段', trigger: 'change' }]
}

// 可用字段列表
const availableFields = [
  { value: 'title', label: '消息标题' },
  { value: 'type', label: '消息类型' },
  { value: 'content', label: '消息内容' },
  { value: 'status', label: '处理状态' },
  { value: 'creator', label: '创建人' },
  { value: 'createTime', label: '创建时间' },
  { value: 'handler', label: '处理人' },
  { value: 'handleTime', label: '处理时间' },
  { value: 'comment', label: '处理意见' }
]

// 消息类型
const messageTypes = [
  { value: 'notification', label: '通知' },
  { value: 'task', label: '任务' },
  { value: 'warning', label: '警告' },
  { value: 'system', label: '系统' }
]

// 处理状态
const processStatus = [
  { value: 'pending', label: '待处理' },
  { value: 'processing', label: '处理中' },
  { value: 'completed', label: '已完成' },
  { value: 'rejected', label: '已驳回' },
  { value: 'cancelled', label: '已取消' }
]

// 初始化数据
onMounted(() => {
  fetchExportTasks()
  fetchExportTemplates()
})

// 获取导出任务列表
const fetchExportTasks = async () => {
  loading.value = true
  try {
    const params = {
      pageNum: pageNum.value,
      pageSize: pageSize.value,
      query: searchQuery.value
    }
    const res = await getExportTaskList(params)
    exportTasks.value = res.data.list
    total.value = res.data.total
  } catch (error) {
    console.error('获取导出任务列表失败:', error)
    ElMessage.error('获取导出任务列表失败')
  } finally {
    loading.value = false
  }
}

// 获取导出模板列表
const fetchExportTemplates = async () => {
  try {
    const res = await getExportTemplateList()
    exportTemplates.value = res.data
  } catch (error) {
    console.error('获取导出模板列表失败:', error)
    ElMessage.error('获取导出模板列表失败')
  }
}

// 搜索处理
const handleSearch = () => {
  pageNum.value = 1
  fetchExportTasks()
}

// 分页处理
const handleSizeChange = (val) => {
  pageSize.value = val
  fetchExportTasks()
}

const handleCurrentChange = (val) => {
  pageNum.value = val
  fetchExportTasks()
}

// 新建导出任务
const handleCreateExport = () => {
  Object.assign(exportForm, {
    id: '',
    name: '',
    templateId: '',
    format: 'excel',
    timeRange: [],
    types: [],
    status: []
  })
  exportDialogVisible.value = true
}

// 提交导出任务
const submitExport = async () => {
  if (!exportFormRef.value) return
  
  try {
    await exportFormRef.value.validate()
    submitting.value = true
    
    const data = {
      ...exportForm,
      startTime: exportForm.timeRange?.[0],
      endTime: exportForm.timeRange?.[1]
    }
    
    if (exportForm.id) {
      await updateExportTask(data)
    } else {
      await createExportTask(data)
    }
    
    ElMessage.success(exportForm.id ? '更新成功' : '创建成功')
    exportDialogVisible.value = false
    fetchExportTasks()
  } catch (error) {
    console.error('提交导出任务失败:', error)
    ElMessage.error(error.message || '提交失败')
  } finally {
    submitting.value = false
  }
}

// 下载导出文件
const handleDownload = async (row) => {
  try {
    const res = await downloadExportFile(row.id)
    const blob = new Blob([res.data], { type: 'application/octet-stream' })
    const link = document.createElement('a')
    link.href = window.URL.createObjectURL(blob)
    link.download = `${row.name}.${row.format}`
    link.click()
    window.URL.revokeObjectURL(link.href)
  } catch (error) {
    console.error('下载文件失败:', error)
    ElMessage.error('下载文件失败')
  }
}

// 重试导出任务
const handleRetry = (row) => {
  ElMessageBox.confirm('确定要重试该导出任务吗？', '提示', {
    type: 'warning'
  }).then(async () => {
    try {
      await retryExportTask(row.id)
      ElMessage.success('重试成功')
      fetchExportTasks()
    } catch (error) {
      console.error('重试失败:', error)
      ElMessage.error('重试失败')
    }
  })
}

// 删除导出任务
const handleDelete = (row) => {
  ElMessageBox.confirm('确定要删除该导出任务吗？', '提示', {
    type: 'warning'
  }).then(async () => {
    try {
      await deleteExportTask(row.id)
      ElMessage.success('删除成功')
      fetchExportTasks()
    } catch (error) {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  })
}

// 新建导出模板
const handleCreateTemplate = () => {
  Object.assign(templateForm, {
    id: '',
    name: '',
    description: '',
    format: 'excel',
    selectedFields: []
  })
  templateDialogVisible.value = true
}

// 编辑导出模板
const handleEditTemplate = (row) => {
  Object.assign(templateForm, {
    id: row.id,
    name: row.name,
    description: row.description,
    format: row.format,
    selectedFields: row.fields.map(f => f.value)
  })
  templateDialogVisible.value = true
}

// 复制导出模板
const handleCopyTemplate = (row) => {
  ElMessageBox.confirm('确定要复制该导出模板吗？', '提示', {
    type: 'warning'
  }).then(async () => {
    try {
      await copyExportTemplate(row.id)
      ElMessage.success('复制成功')
      fetchExportTemplates()
    } catch (error) {
      console.error('复制失败:', error)
      ElMessage.error('复制失败')
    }
  })
}

// 删除导出模板
const handleDeleteTemplate = (row) => {
  ElMessageBox.confirm('确定要删除该导出模板吗？', '提示', {
    type: 'warning'
  }).then(async () => {
    try {
      await deleteExportTemplate(row.id)
      ElMessage.success('删除成功')
      fetchExportTemplates()
    } catch (error) {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  })
}

// 提交导出模板
const submitTemplate = async () => {
  if (!templateFormRef.value) return
  
  try {
    await templateFormRef.value.validate()
    submitting.value = true
    
    const data = {
      ...templateForm,
      fields: templateForm.selectedFields.map(value => {
        const field = availableFields.find(f => f.value === value)
        return {
          value: field.value,
          label: field.label
        }
      })
    }
    
    if (templateForm.id) {
      await updateExportTemplate(data)
    } else {
      await createExportTemplate(data)
    }
    
    ElMessage.success(templateForm.id ? '更新成功' : '创建成功')
    templateDialogVisible.value = false
    fetchExportTemplates()
  } catch (error) {
    console.error('提交导出模板失败:', error)
    ElMessage.error(error.message || '提交失败')
  } finally {
    submitting.value = false
  }
}

// 移动字段顺序
const moveField = (direction) => {
  const fields = templateForm.selectedFields
  const index = fields.indexOf(templateForm.currentField)
  if (direction === 'up' && index > 0) {
    [fields[index], fields[index - 1]] = [fields[index - 1], fields[index]]
  } else if (direction === 'down' && index < fields.length - 1) {
    [fields[index], fields[index + 1]] = [fields[index + 1], fields[index]]
  }
}

// 工具函数
const getStatusType = (status) => {
  const typeMap = {
    pending: 'info',
    processing: 'primary',
    completed: 'success',
    failed: 'danger'
  }
  return typeMap[status] || ''
}

const getStatusLabel = (status) => {
  const labelMap = {
    pending: '等待中',
    processing: '处理中',
    completed: '已完成',
    failed: '失败'
  }
  return labelMap[status] || status
}

const getProgressStatus = (status) => {
  const statusMap = {
    pending: '',
    processing: '',
    completed: 'success',
    failed: 'exception'
  }
  return statusMap[status] || ''
}
</script>

<style lang="scss" scoped>
.message-export {
  padding: 20px;

  .export-card {
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 16px;

      .header-left {
        display: flex;
        align-items: center;
        gap: 16px;

        .search-input {
          width: 200px;
        }
      }
    }

    .template-header {
      margin-bottom: 16px;
    }

    .fields-container {
      display: flex;
      gap: 16px;

      .fields-list {
        flex: 1;
        border: 1px solid #dcdfe6;
        border-radius: 4px;
        padding: 16px;

        .el-checkbox-group {
          display: flex;
          flex-direction: column;
          gap: 8px;
        }
      }

      .fields-actions {
        display: flex;
        flex-direction: column;
        justify-content: center;
      }
    }

    .pagination-container {
      margin-top: 20px;
      display: flex;
      justify-content: flex-end;
    }
  }
}
</style> 